package com.me.springcloud.feign.ssl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.KeyStore;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

/**
 * @project mgwCore
 * @description:��ݷ���ʵ��
 * @author cen
 * @create_time:Jun 22, 2009
 * @modify_time:Jun 22, 2009
 */
public class HttpSSLUtil {

	public static void main(String[] args) throws Exception {
		System.setProperty("jsse.enableSNIExtension", "false");
		readFromStream(HttpSSLUtil.post(FeignSSLTest.getData()));
	}

	public static InputStream post(String xml) throws Exception {
		File certFile = new File(Constants.JKS_PATH);
		KeyStore ks = KeyStore.getInstance("JKS");
		ks.load(new FileInputStream(certFile), Constants.JKS_PASS.toCharArray());
		
		
		KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		kmf.init(ks, Constants.JKS_PASS.toCharArray());

		TrustManager[] tm = { new MyX509TrustManager() };

		
		SSLContext sslContext = SSLContext.getInstance("SSL");
		sslContext.init(kmf.getKeyManagers(), tm, null);

		SSLSocketFactory factory = sslContext.getSocketFactory();

		URL url = new URL("https://mas.99bill.com:443/cnp/getDynNum");
		HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection();
		urlc.setSSLSocketFactory(factory);
		urlc.setDoOutput(true);
		urlc.setDoInput(true);
		urlc.setReadTimeout(30000);

		String authString = "812310063001078" + ":" + Constants.JKS_PASS;
		String auth = "Basic " + Base64Binrary.encodeBase64Binrary(authString.getBytes());
		urlc.setRequestProperty("Authorization", auth);

		OutputStream out = urlc.getOutputStream();
		out.write(xml.getBytes());
		out.flush();
		out.close();

		return urlc.getInputStream();
	}

	public static void readFromStream(InputStream ss) throws Exception {
		StringBuilder builder = new StringBuilder();
		BufferedReader in = new BufferedReader(new InputStreamReader(ss, "UTF-8"));
		String line;
		while ((line = in.readLine()) != null) {
			builder.append("\n").append(line);
		}

		System.out.println(builder.toString());
	}
}